package com.yonyou.pmclouds.basecom.bp.template;

import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import org.apache.ibatis.exceptions.PersistenceException;

import java.util.ArrayList;
import java.util.List;

public abstract class MultiOperateBpTemplate<T> {
    protected List<MultiProcessor<T>> beforeProcessor = new ArrayList<>();
    protected List<MultiProcessor<T>> afterProcessor = new ArrayList<>();

    protected abstract void operateDirect(T[] vos, T[] origs);

    protected T[] getOrigVO(T[] vos) throws BusinessException {
        return null;
    }

    protected void before(T[] vos, T[] origs) throws BusinessException {
        for (int i = 0; i < beforeProcessor.size(); i++) {
        	beforeProcessor.get(i).process(vos, origs);
        }
    }

    protected void after(T[] vos, T[] origs) throws BusinessException {
        for (int i = 0; i < afterProcessor.size(); i++) {
        	afterProcessor.get(i).process(vos, origs);
        }
    }

    public MultiOperateBpTemplate addBeforeProcessor(MultiProcessor<T> processor) {
        beforeProcessor.add(processor);
        return this;
    }


    public MultiOperateBpTemplate addAfterProcessor(MultiProcessor<T> processor) {
        afterProcessor.add(processor);
        return this;
    }

    protected T[] execute(T[] vos) throws BusinessException {
        try {
            T[] origs = getOrigVO(vos);
            before(vos, origs);
            operateDirect(vos, origs);
            after(vos, origs);
        } catch (PersistenceException ex) {
            throw new BusinessException("数据库查询错误!");
        }
        return vos;
    }

}
